#!/bin/bash
#
# Developed by Fred Weinhaus 12/21/2007 .......... revised 4/25/2015
#
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#
# USAGE: pseudocolor [-o offset] [-i increment] [-d delay] [ -r resize] [-v] infile [outfile]
# USAGE: pseudocolor [-h or -help]
#
# OPTIONS:
#
# -o     offset       offset of rainbow colors (single frame only); 
#                     0 to 255; default=0
# -i     increment    incremental shift of rainbow colors per animation frame; 
#                     -128 to 128; default=-8 if no outfile provided;
#                     value of -8 for animation creates 33 frames;
#                     default=0 with outfile indicates single frame output           
# -d     delay        time delay per animation frame (ms); delay >= 0; default=10
# -r     resize       image resize percentage; resize > 0; 
#                     default=100 (unchanged)
# -v                  indicates to view (display) the animation automatically
# outfile             if no oufile is provided, a default 33 frame animation will 
#                     be generated and viewed (displayed) automatically without 
#                     specifying the -v option
#
###
#
# NAME: PSEUDOCOLOR 
# 
# PURPOSE: To generate a pseudocolored image or pseudocolored animation from grayscale 
# image using a rainbow colored transformation. 
# 
# DESCRIPTION: PSEUDOCOLOR generates a rainbow colored look up table image and applies 
# it to a grayscale image to generate either a single frame psuedocolored output 
# image or a pseudocolored animation. Each frame of the animation uses a different 
# incremental roll of the rainbow color look up table. For a single frame pseudocolored 
# output, the rainbow color look up table may be rolled by a user specified amount.
# The animation may be viewed (displayed) automatically with or without the saved 
# animation file.
# 
# 
# OPTIONS: 
# 
# 
# -o offset ... OFFSET is the pixel roll amount of the rainbow color look up
# table to be used for a single frame output image. If an animation is to be 
# generated by specifying an increment value other than 0, then the offset 
# will be ignored. Values for offset may be integers between 0 and 255 for 
# the length 256 look up table. The default=0.
# 
# -i increment ... INCREMENT is the pixel roll amount of the rainbow color 
# look up table to be used for each new frame of the animation. Increment 
# values should be integers between -128 and 128. The sign indicates which 
# direction to roll the look up table. The suggested value of -8 creates a 
# 33 frame animation. The default=0 indicates that a single frame output image 
# will be generated.
# 
# -d delay ... DELAY is the time delay in msec between frames in the animation. 
# Values are integers greater than or equal to zero. The default=10. Note that 
# the animation will be created to loop forever. Delay is ignored if a single 
# frame output is to be generated.
# 
# -r resize ... RESIZE allows the output animation to made larger or smaller than 
# the input image size. The values are integers greater than 0 representing the 
# resize percentage. The default=100 which leaves the animation the same size as 
# the input image.
# 
# outfile ... OUTFILE, if provided for an animation, must be in a format such as 
# gif that supports multiframe animations.
# 
# -v ... Specifies that along with the output animation, the animation is to be 
# viewed (displayed) automatically before the script is ended. If no output 
# animation file is provided, the animation will be created and viewed 
# automatically even if the -v option is not specified. This parameter is 
# ignored if the output is a single frame image.
# 
# CAVEAT: No guarantee that this script will work on all platforms, 
# nor that trapping of inconsistent parameters is complete and 
# foolproof. Use At Your Own Risk. 
# 
######
#
# set default values
offset=0    # roll offset (for single frame output)
incr=0      # roll increment (for animation)
delay=10    # time delay for animation
resize=""   # resize
view="no"   # automatic view (display)
wd=256      # lut width
ht=1        # lut height
L=255       # lightness value for generating the rainbow
S=255       # saturation value for generating the rainbow

# set directory for temporary files
dir="."    # suggestions are dir="." or dir="/tmp"

# set up functions to report Usage and Usage with Description
PROGNAME=`type $0 | awk '{print $3}'`  # search for executable on path
PROGDIR=`dirname $PROGNAME`            # extract directory of program
PROGNAME=`basename $PROGNAME`          # base name of program
usage1() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^###/g;  /^#/!q;  s/^#//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}
usage2() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^######/g;  /^#/!q;  s/^#*//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}

# function to report error messages
errMsg()
	{
	echo ""
	echo $1
	echo ""
	usage1
	exit 1
	}

# function to test for minus at start of value of second part of option 1 or 2
checkMinus()
	{
	test=`echo "$1" | grep -c '^-.*$'`   # returns 1 if match; 0 otherwise
    [ $test -eq 1 ] && errMsg "$errorMsg"
	}

# test for correct number of arguments and get values
if [ $# -eq 0 ]
	then
	# help information
   echo ""
   usage2
   exit 0
elif [ $# -gt 9 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		  -h|-help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-o)    # roll offset
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID OFFSET SPECIFICATION ---"
					   checkMinus "$1"
					   offset="$1"
					   offsettest=`expr "$offset" : '^[0-9][0-9]*$'`
		   			   offsettestA=`echo "$offset < 0" | bc`
		   			   offsettestB=`echo "$offset > 255" | bc`
		   			   [ $offsettest -eq 0 ] && errMsg "--- OFFSET=$offset MUST BE AN INTEGER ---"
					   [ $offsettestA -eq 1 -o $offsettestB -eq 1 ] && errMsg "--- OFFSET=$offset MUST BE GREATER THAN OR EQUAL 0 AND LESS THAN OR EQUAL 255 ---"
					   ;;
				-i)    # roll increment
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   #errorMsg="--- INVALID INCREMENT SPECIFICATION ---"
					   #checkMinus "$1"
					   incr="$1"
					   incrtest=`expr "$incr" : '^[0-9\-][0-9]*$'`
		   			   incrtestA=`echo "$incr < -128" | bc`
		   			   incrtestB=`echo "$incr > 128" | bc`
		   			   [ $incrtest -eq 0 ] && errMsg "--- INCREMENT=$incr MUST BE AN INTEGER ---"
					   [ $incrtestA -eq 1 -o $incrtestB -eq 1 ] && errMsg "--- INCREMENT=$incr MUST BE GREATER THAN OR EQUAL -128 AND LESS THAN OR EQUAL 128 ---"
					   ;;
				-d)    # delay
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID DELAY SPECIFICATION ---"
					   checkMinus "$1"
					   delay="$1"
					   delaytest=`expr "$delay" : '^[0-9][0-9]*$'`
		   			   delaytestA=`echo "$delay < 1" | bc`
		   			   [ $delaytest -eq 0 ] && errMsg "--- DELAY=$delay MUST BE AN INTEGER ---"
					   [ $delaytestA -eq 1 ] && errMsg "--- DELAY=$delay MUST BE GREATER THAN 0 ---"
					   ;;
				-r)    # resize
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID RESIZE SPECIFICATION ---"
					   checkMinus "$1"
					   resize="$1"
					   resizetest=`expr "$resize" : '^[0-9][0-9]*$'`
		   			   resizetestA=`echo "$resize < 1" | bc`
		   			   [ $resizetest -eq 0 ] && errMsg "--- RESIZE=$resize MUST BE AN INTEGER ---"
					   [ $resizetestA -eq 1 ] && errMsg "--- RESIZE=$resize MUST BE GREATER THAN 0 ---"
					   resize="-resize $1%"
					   ;;
				-v)    # view
					   view="yes"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
				 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile and outfile
	infile="$1"
	outfile="$2"
fi

# test that infile provided
[ "$infile" = "" ] && errMsg "NO INPUT FILE SPECIFIED"


# setup temporary images and auto delete upon exit
# use mpc/cache to hold input image temporarily in memory
tmpA="$dir/coloration_$$.mpc"
tmpB="$dir/coloration_$$.cache"
tmp0="$dir/coloration_0_$$.png"
tmp1="$dir/coloration_1_$$.png"
tmp2="$dir/coloration_2_$$.png"
tmp3="$dir/coloration_3_$$.png"
tmp4="$dir/coloration_4_$$.gif"
trap "rm -f $tmpA $tmpB $tmp0 $tmp1 $tmp2 $tmp3 $tmp4;" 0
trap "rm -f $tmpA $tmpB $tmp0 $tmp1 $tmp2 $tmp3 $tmp4; exit 1" 1 2 3 15
trap "rm -f $tmpA $tmpB $tmp0 $tmp1 $tmp2 $tmp3 $tmp4; exit 1" ERR

if convert -quiet "$infile" $resize +repage "$tmpA"
	then
	: ' do nothing '
	else
		errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"
fi

# get im_version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

# colorspace RGB and sRGB swapped between 6.7.5.5 and 6.7.6.7 
# though probably not resolved until the latter
# then -colorspace gray changed to linear between 6.7.6.7 and 6.7.8.2 
# then -separate converted to linear gray channels between 6.7.6.7 and 6.7.8.2,
# though probably not resolved until the latter
# so -colorspace HSL/HSB -separate and -colorspace gray became linear
# but we need to use -set colorspace RGB before using them at appropriate times
# so that results stay as in original script
# The following was determined from various version tests using pseudocolor.
# with IM 6.7.4.10, 6.7.6.10, 6.7.9.0
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
if [ "$im_version" -lt "06070606" -o "$im_version" -gt "06070707" ]; then
	cspace="RGB"
else
	cspace="sRGB"
fi
# no need for setcspace for grayscale or channels after 6.8.5.4
if [ "$im_version" -gt "06080504" ]; then
	setcspace=""
	cspace="sRGB"
fi


# create hue channel
convert -size ${ht}x${wd} gradient: $tmp0

# create saturation channel
convert -size ${ht}x${wd} xc:"rgb($S,$S,$S)" $setcspace -channel Green -separate $tmp1

# create lightness channel
convert -size ${ht}x${wd} xc:"rgb($L,$L,$L)" $setcspace -channel Blue -separate $tmp2

# combine channels to form rainbow lut
convert $tmp0 -colorspace HSB $tmp0 \
	-compose CopyRed -composite $tmp1 \
	-compose CopyGreen -composite $tmp2 \
	-compose CopyBlue -composite -colorspace $cspace \
	-rotate 90 $tmp3


# process image

im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d;  s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`

if [ $incr -eq 0 -a "$outfile" != "" ]
	then
	# single frame output
	if [ "$im_version" -ge "06030507" ]
		then 
		convert $tmpA \( $tmp3 -roll -$offset+0 \) -clut "$outfile"
	else
		convert $tmpA $tmp3 -fx 'v.p{u*v.w,0}' "$outfile"
	fi
else
	# animation
	[ "$outfile" = "" -a $incr -eq 0 ] && incr=8
	numframes=`echo "scale=0; (1 + ($wd / $incr)) / 1" | bc`
	echo ""
	echo "Please Wait - $numframes Frames Being Created"
	echo ""
	if [ "$im_version" -ge "06030507" ]
		then 
		rotamt=0
		convert $tmpA $tmp3 -clut $tmp4
		rotamt=`expr $rotamt + $incr`
		i=1
		echo $i
		while [ $rotamt -le $wd ]
			do
			convert $tmpA \( $tmp3 -roll -$rotamt+0 \) -clut miff:- |\
				convert -delay $delay $tmp4 -page +0+0 - -page +0+0 $tmp4
			rotamt=`expr $rotamt + $incr`
			i=`expr $i + 1`
			echo $i
		done
			if [ "$outfile" != "" ]
				then
				convert $tmp4 -loop 0 $outfile
			fi
			if [ "$view" = "yes" -o "$outfile" = "" ]
				then
				animate $tmp4
			fi
	else
		rotamt=0
		convert $tmpA $tmp3 -clut $tmp4
		rotamt=`expr $rotamt + $incr`
		i=1
		echo $i
		while [ $rotamt -le $wd ]
			do
			convert $tmpA \( $tmp3 -roll -$rotamt+0 \) -fx 'v.p{u*v.w,0}' miff:- |\
				convert -delay $delay $tmp4 -page +0+0 - -page +0+0 $tmp4
			rotamt=`expr $rotamt + $incr`
			i=`expr $i + 1`
			echo $i
		done
			if [ "$outfile" != "" ]
				then
				convert $tmp4 -loop 0 "$outfile"
			fi
			if [ "$view" = "yes" -o "$outfile" = "" ]
				then
				animate $tmp4
			fi
	fi
fi
exit 0
